import vm from "../main";

/**
 *  获取地址栏参数 返回对象
 * @param url 地址
 * @returns {{}}
 */
export const parseQueryString = (url = window.location.href) => {
  let reg_url = /^[^?]+\?([\w\W]+)$/,
    reg_para = /([^&=]+)=([\w\W]*?)(&|$|#)/g,
    arr_url = reg_url.exec(url),
    ret = {};
  if (arr_url && arr_url[1]) {
    let str_para = arr_url[1],
      result;
    while ((result = reg_para.exec(str_para)) != null) {
      ret[result[1]] = result[2];
    }
  }
  return ret;
};

/**
 * 将一维数组转换成树形格式
 * @param data
 * @returns {[]}
 */
export function toTree(data) {
  const result = [];
  if (!Array.isArray(data)) {
    return result;
  }
  data.forEach(item => {
    delete item.children;
  });
  const map = {};
  data.forEach(item => {
    map[item.id] = item;
  });
  data.forEach(item => {
    const parent = map[item.parentId];
    if (parent) {
      item.key = item.id;
      item.path = item.url;
      (parent.children || (parent.children = [])).push(item);
    } else {
      item.key = item.id;
      item.path = item.url;
      result.push(item);
    }
  });
  return result;
}

/**
 * 资源权限校验
 * @param url 按钮请求地址
 * @returns {boolean}
 */
export function btnShowAuthority(url) {
  let btnArr = vm.$store.state.btnControl.btnArray;
  if (vm.$store.state.btnControl.roleName === "主账号") return true;
  return btnArr.some(item => {
    return item.url === url;
  });
}
